<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/13
 * Time: 11:33
 */

namespace app\im\model;

/**
 * @method belongsTo(string $string)
 */
class Chat extends ImBase
{
    /**
     * 一对一获取用户信息
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo("user");
    }


    // 格式化
    public function getContentAttr($value, $data)
    {

        if (isset($data["chat_type"]) && in_array($data["chat_type"], [2, 3])) {
            $value = attach($value);
        }
        return $value;
    }

    // 格式化内容
    public function scopeContent($query)
    {
        // withAttr 不能再使用模型的查询方法，必须使用Db类的查询方法。
        // 不用 getContentAttr 因为避免全局应用
        $query->withAttr('content', function ($value, $data) {
            $value = str_replace('|||', ' ', $value);
            $value = subtext($value, 12);

            $array = [" ", $value, "[图片]", "[语音]", "[语音]"];
            return $array[$data["chat_type"]];
        });
    }

    // 获取聊天记录
    public static function getHistory($param)
    {
        // 获取房间号
        $root_id = $param["root_id"] ?? 0;
        $root_id = $root_id ?: ChatLists::getRootID($param["user_id"], $param["obj_uid"]);

        $history = [];
        $have_more = 0;
        if ($root_id) {
            // 分页
            $page = $param["page"] ?? 1;
            $limit = $param["limit"] ?? 10;
            // 被删除IDs
            $deleted_ids = ChatDeletion::getByUID($param["user_id"]);

            // 查询
            $lists = self::lists($param)->with("user")
                ->where("root_id", $root_id)
                ->where("id", "not in", $deleted_ids)
                ->all()
                ->each(function ($item) use ($param) {
                    $item->is_mine =
                        (int)($param["user_id"] == $item["user_id"]);
                })
                ->toArray();

            // 排序
            $sort = $page > 1 ? SORT_DESC : SORT_ASC;
            $history = array_sort($lists, 'id', $sort);
            // 根据 have_more 显示加载更多按钮
            $have_more = self::where("root_id", $root_id)
                    ->where("id", "not in", $deleted_ids)
                    ->count() <=> $page * $limit;

        }

        $obj_user = User::get($param["obj_uid"]);

        return compact("root_id", "have_more"
            , "obj_user", "history");
    }


    /**
     * 聊天内容持久化
     * @param $input
     * @return Chat
     * @throws \think\Exception
     */
    public static function newMess($input)
    {

        $user_id = $input["user_id"];
        // 获取房间号
        $root_id = $input["root_id"] ?: ChatRoot::chatInit($input);

        // 新增聊天
        $chat = new self;
        $chat->chat_type = $input["chat_type"] ?? 1;
        $chat->user_id = $user_id;
        $chat->root_id = $root_id;
        $chat->content = $input["content"];
        // 语音时长
        $chat->seconds = $input["seconds"] ?? null;

        $chat->save();

        // 列表未读数 +1
        ChatLists::incUnreadNum($user_id, $root_id);

        // 恢复被删除的列表
        ChatLists::where("root_id", $root_id)
            ->setField("is_del", 0);

        return $chat;
    }
}